package com.halflife.comeElectricity.member.rider;

import com.halflife.comeElectricity.battery.Battery;
import com.halflife.comeElectricity.battery.BatteryRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.framework.participant.user.UserView;
import com.halflife.shiro.utils.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class RiderOrderAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private RiderOrderRepository riderOrderRepository;
    @Resource
    private BatteryRepository batteryRepository;

    @RequestMapping("/riderOrder/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) throws Exception{

        UserView user = ShiroUtil.getUserView(request);
        MapHandler.handleMap(queryParam);
        queryParam.put("departmentId", user.getDepartmentId());
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        queryParam.put("endSql", "t.status>=0");
        queryParam.put("orderSql", "t.beginDate desc ,t.id desc");
        Map param = new HashMap();
        param.putAll(queryParam);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (queryParam.containsKey("beginDate")) {
            String beginDate = (String) queryParam.get("beginDate");
            Date date = sdf.parse(beginDate);
            queryParam.put("beginDate", date.getTime());
        }
        if (queryParam.containsKey("endDate")) {
            String endDate = (String) queryParam.get("endDate");
            Date date = sdf.parse(endDate);
            queryParam.put("endDate", date.getTime());
        }

        int totalCount = riderOrderRepository.selectCount(queryParam);
        List<RiderOrder> list = riderOrderRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",param);
        return "riderOrder/list";
    }

    @RequestMapping("/riderOrder/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        RiderOrder riderOrder = new RiderOrder();
        if(id!=null){
            riderOrder = riderOrderRepository.selectByPrimaryKey(id);
        }
        model.addAttribute("riderOrder",riderOrder);
        return "riderOrder/operate";
    }

    @PostMapping("/riderOrder/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(RiderOrder riderOrder, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            if(riderOrder.getId()!=null){
                if (riderOrder.getStatus() == 1 && riderOrder.getEndDate() == null) {
                    riderOrder.setEndDate(new Date().getTime());
                    List<Battery> list =  batteryRepository.selectMany("select * from t_battery t where t.no='"+riderOrder.getBatteryNo()+"'");
                    if (list.size() > 0) {
                        Battery battery = list.get(0);
                        battery.setId(battery.getId());
                        battery.setStatus(0);
                        battery.setOrderId(null);
                        batteryRepository.updateByPrimaryKey(battery);
                    }
                }
                riderOrderRepository.updateByPrimaryKeySelective(riderOrder);
            }else {
                riderOrder.init();
                Integer a = riderOrderRepository.insert(riderOrder);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/riderOrder/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            RiderOrder riderOrder = new RiderOrder();
            riderOrder.setId(id);
            riderOrder.setValid(Boolean.FALSE);
            riderOrderRepository.updateByPrimaryKeySelective(riderOrder);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
